package com.project.poetry.service.job;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.project.poetry.common.util.CommonUtil;
import com.project.poetry.service.entity.po.poetry.PoetryPO;
import com.project.poetry.service.entity.po.sentence.PoetrySentencePO;
import com.project.poetry.service.service.PoetrySentenceService;
import com.project.poetry.service.service.PoetryService;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author mengxj
 */
@Component("syncSentence")
public class SyncSentenceJob {

    @Resource
    private PoetrySentenceService poetrySentenceService;

    @Resource
    private PoetryService poetryService;

    @Transactional(rollbackFor = Exception.class)
    @SuppressWarnings("unused")
    public void sync(String onTime){
        List<PoetrySentencePO> res = new ArrayList<>();
        LambdaQueryWrapper<PoetryPO> wrapper = new QueryWrapper<PoetryPO>().lambda();
        wrapper.eq(PoetryPO::getSyncStatus, 0).last(String.format("limit %s", onTime));
        List<PoetryPO> poetryList = this.poetryService.list(wrapper);
        if(CommonUtil.isEmpty(poetryList)){
            return;
        }
        poetryList.stream().peek(po -> po.setSyncStatus(1)).forEach(poetry -> {
            LambdaQueryWrapper<PoetrySentencePO> wrap = new QueryWrapper<PoetrySentencePO>().lambda();
            wrap.eq(PoetrySentencePO::getPoetryId, poetry.getId());
            this.poetrySentenceService.remove(wrap);
            this.poetryService.updateById(poetry);
        });
        for(PoetryPO poetry: poetryList){
            AtomicInteger number = new AtomicInteger(1);
            List<String> sentences = JSON.parseArray(poetry.getContent(), String.class);
            Long poetryId = poetry.getId();
            sentences.stream().filter(StrUtil :: isNotEmpty).forEach(sentence -> {
                PoetrySentencePO ps = new PoetrySentencePO();
                res.add(ps);
                ps.setOrderNumber(number.getAndIncrement());
                ps.setPoetryId(poetryId);
                ps.setSentence(sentence);
            });
        }
        this.poetrySentenceService.saveBatch(res);
    }
}
